package com.example.managemyself.ui.profile;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;

import com.example.managemyself.R;
import com.example.managemyself.data.model.User;
import com.example.managemyself.util.UserManager;
import com.example.managemyself.viewmodel.ProfileViewModel;
import com.google.android.material.switchmaterial.SwitchMaterial;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 用户资料编辑Activity - 增强版
 */
public class EditProfileActivity extends AppCompatActivity {
    
    private static final int PICK_IMAGE_REQUEST = 1;
    
    private ProfileViewModel viewModel;
    private User currentUser;
    
    // UI组件 - 基本信息
    private ImageView ivAvatar;
    private EditText etUsername;
    private EditText etEmail;
    private EditText etPhone;
    private EditText etBirthday;
    private RadioGroup rgGender;
    private RadioButton rbMale;
    private RadioButton rbFemale;
    private EditText etBio;
    
    // UI组件 - 个性化设置
    private Spinner spinnerConstellation;
    private EditText etHobbies;
    private EditText etOccupation;
    private EditText etCity;
    
    // UI组件 - 隐私设置
    private SwitchMaterial switchPublicBirthday;
    private SwitchMaterial switchPublicContact;
    
    // UI组件 - 按钮
    private Button btnSave;
    private Button btnCancel;
    
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private Calendar selectedDate = Calendar.getInstance();
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);
        
        initViews();
        setupToolbar();
        setupViewModel();
        setupSpinners();
        loadUserData();
        setupClickListeners();
    }
    
    private void initViews() {
        // 基本信息
        ivAvatar = findViewById(R.id.iv_avatar);
        etUsername = findViewById(R.id.et_username);
        etEmail = findViewById(R.id.et_email);
        etPhone = findViewById(R.id.et_phone);
        etBirthday = findViewById(R.id.et_birthday);
        rgGender = findViewById(R.id.rg_gender);
        rbMale = findViewById(R.id.rb_male);
        rbFemale = findViewById(R.id.rb_female);
        etBio = findViewById(R.id.et_bio);
        
        // 个性化设置
        spinnerConstellation = findViewById(R.id.spinner_constellation);
        etHobbies = findViewById(R.id.et_hobbies);
        etOccupation = findViewById(R.id.et_occupation);
        etCity = findViewById(R.id.et_city);
        
        // 隐私设置
        switchPublicBirthday = findViewById(R.id.switch_public_birthday);
        switchPublicContact = findViewById(R.id.switch_public_contact);
        
        // 按钮
        btnSave = findViewById(R.id.btn_save);
        btnCancel = findViewById(R.id.btn_cancel);
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("编辑个人资料");
        }
    }
    
    private void setupViewModel() {
        viewModel = new ViewModelProvider(this).get(ProfileViewModel.class);
    }
    
    private void setupSpinners() {
        // 设置星座选择器
        ArrayAdapter<CharSequence> constellationAdapter = ArrayAdapter.createFromResource(
                this, R.array.constellation_options, android.R.layout.simple_spinner_item);
        constellationAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerConstellation.setAdapter(constellationAdapter);
    }
    
    private void loadUserData() {
        currentUser = UserManager.getInstance().getCurrentUser();
        if (currentUser != null) {
            etUsername.setText(currentUser.getUsername());
            etEmail.setText(currentUser.getEmail());
            
            // 加载扩展信息
            loadExtendedUserInfo();
        }
    }
    
    private void loadExtendedUserInfo() {
        // 从数据库加载用户扩展信息
        viewModel.getUser(currentUser.getId()).observe(this, user -> {
            if (user != null) {
                // 设置基本信息
                if (user.getPhone() != null) etPhone.setText(user.getPhone());
                if (user.getBirthday() != null) {
                    etBirthday.setText(dateFormat.format(user.getBirthday()));
                }
                if (user.getBio() != null) etBio.setText(user.getBio());
                
                // 设置性别
                if ("male".equals(user.getGender())) {
                    rbMale.setChecked(true);
                } else if ("female".equals(user.getGender())) {
                    rbFemale.setChecked(true);
                }
                
                // 设置个性化信息
                if (user.getHobbies() != null) etHobbies.setText(user.getHobbies());
                if (user.getOccupation() != null) etOccupation.setText(user.getOccupation());
                if (user.getCity() != null) etCity.setText(user.getCity());
                
                // 设置星座
                if (user.getConstellation() != null && !user.getConstellation().isEmpty()) {
                    String[] constellations = getResources().getStringArray(R.array.constellation_options);
                    for (int i = 0; i < constellations.length; i++) {
                        if (constellations[i].equals(user.getConstellation())) {
                            spinnerConstellation.setSelection(i);
                            break;
                        }
                    }
                }
                
                // 设置隐私选项
                switchPublicBirthday.setChecked(user.isPublicBirthday());
                switchPublicContact.setChecked(user.isPublicContact());
            }
        });
    }
    
    private void setupClickListeners() {
        ivAvatar.setOnClickListener(v -> selectAvatar());
        etBirthday.setOnClickListener(v -> showDatePicker());
        btnSave.setOnClickListener(v -> saveProfile());
        btnCancel.setOnClickListener(v -> finish());
    }
    
    private void selectAvatar() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }
    
    private void showDatePicker() {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    selectedDate.set(year, month, dayOfMonth);
                    etBirthday.setText(dateFormat.format(selectedDate.getTime()));
                    
                    // 自动计算并设置星座
                    String constellation = calculateConstellation(month + 1, dayOfMonth);
                    setConstellationSelection(constellation);
                },
                selectedDate.get(Calendar.YEAR),
                selectedDate.get(Calendar.MONTH),
                selectedDate.get(Calendar.DAY_OF_MONTH)
        );
        
        // 设置最大日期为今天
        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
        datePickerDialog.show();
    }
    
    private String calculateConstellation(int month, int day) {
        // 根据生日计算星座
        if ((month == 3 && day >= 21) || (month == 4 && day <= 19)) return "白羊座";
        if ((month == 4 && day >= 20) || (month == 5 && day <= 20)) return "金牛座";
        if ((month == 5 && day >= 21) || (month == 6 && day <= 21)) return "双子座";
        if ((month == 6 && day >= 22) || (month == 7 && day <= 22)) return "巨蟹座";
        if ((month == 7 && day >= 23) || (month == 8 && day <= 22)) return "狮子座";
        if ((month == 8 && day >= 23) || (month == 9 && day <= 22)) return "处女座";
        if ((month == 9 && day >= 23) || (month == 10 && day <= 23)) return "天秤座";
        if ((month == 10 && day >= 24) || (month == 11 && day <= 22)) return "天蝎座";
        if ((month == 11 && day >= 23) || (month == 12 && day <= 21)) return "射手座";
        if ((month == 12 && day >= 22) || (month == 1 && day <= 19)) return "摩羯座";
        if ((month == 1 && day >= 20) || (month == 2 && day <= 18)) return "水瓶座";
        if ((month == 2 && day >= 19) || (month == 3 && day <= 20)) return "双鱼座";
        return "";
    }
    
    private void setConstellationSelection(String constellation) {
        if (!constellation.isEmpty()) {
            String[] constellations = getResources().getStringArray(R.array.constellation_options);
            for (int i = 0; i < constellations.length; i++) {
                if (constellations[i].equals(constellation)) {
                    spinnerConstellation.setSelection(i);
                    Toast.makeText(this, "已自动设置星座：" + constellation, Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }
    }
    
    private void saveProfile() {
        if (!validateInput()) {
            return;
        }
        
        // 获取基本信息
        String username = etUsername.getText().toString().trim();
        String email = etEmail.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String birthdayStr = etBirthday.getText().toString().trim();
        String bio = etBio.getText().toString().trim();
        
        String gender = "";
        if (rbMale.isChecked()) {
            gender = "male";
        } else if (rbFemale.isChecked()) {
            gender = "female";
        }
        
        // 获取个性化信息
        String constellation = spinnerConstellation.getSelectedItem().toString();
        String hobbies = etHobbies.getText().toString().trim();
        String occupation = etOccupation.getText().toString().trim();
        String city = etCity.getText().toString().trim();
        
        // 获取隐私设置
        boolean publicBirthday = switchPublicBirthday.isChecked();
        boolean publicContact = switchPublicContact.isChecked();
        
        // 更新用户信息
        currentUser.setUsername(username);
        currentUser.setEmail(email);
        currentUser.setPhone(phone);
        currentUser.setGender(gender);
        currentUser.setBio(bio);
        currentUser.setConstellation(constellation);
        currentUser.setHobbies(hobbies);
        currentUser.setOccupation(occupation);
        currentUser.setCity(city);
        currentUser.setPublicBirthday(publicBirthday);
        currentUser.setPublicContact(publicContact);
        
        // 解析生日
        if (!birthdayStr.isEmpty()) {
            try {
                Date birthday = dateFormat.parse(birthdayStr);
                currentUser.setBirthday(birthday);
            } catch (Exception e) {
                Toast.makeText(this, "生日格式错误", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        
        // 保存到数据库
        viewModel.updateUser(currentUser).observe(this, success -> {
            if (success) {
                // 更新UserManager中的用户信息
                UserManager.getInstance().updateCurrentUser(currentUser);
                Toast.makeText(this, "个人资料已保存", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(this, "保存失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });
    }
    

    
    private boolean validateInput() {
        String username = etUsername.getText().toString().trim();
        String email = etEmail.getText().toString().trim();
        
        if (TextUtils.isEmpty(username)) {
            etUsername.setError("用户名不能为空");
            etUsername.requestFocus();
            return false;
        }
        
        if (username.length() < 2) {
            etUsername.setError("用户名至少需要2个字符");
            etUsername.requestFocus();
            return false;
        }
        
        if (TextUtils.isEmpty(email)) {
            etEmail.setError("邮箱不能为空");
            etEmail.requestFocus();
            return false;
        }
        
        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            etEmail.setError("请输入有效的邮箱地址");
            etEmail.requestFocus();
            return false;
        }
        
        // 验证手机号（如果填写了）
        String phone = etPhone.getText().toString().trim();
        if (!phone.isEmpty() && !phone.matches("^1[3-9]\\d{9}$")) {
            etPhone.setError("请输入有效的手机号");
            etPhone.requestFocus();
            return false;
        }
        
        return true;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            if (imageUri != null) {
                ivAvatar.setImageURI(imageUri);
                saveAvatarUri(imageUri.toString());
            }
        }
    }
    
    private void saveAvatarUri(String avatarUri) {
        android.content.SharedPreferences prefs = getSharedPreferences("user_profile", MODE_PRIVATE);
        prefs.edit().putString("avatar_" + currentUser.getId(), avatarUri).apply();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 